using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using CoachingOrganizer.Logic.Models.Common;
using CoachingOrganizer.Android.Helpers;
using CoachingOrganizer.Android.Adapters;

namespace CoachingOrganizer.Android.Activities
{
    [Activity(Label = "@string/ApplicationName")]
    public class PeriodDetailsActivity : Activity
    {
        private PeriodModel _model;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            _model = UIHelper.GetActivityModel<PeriodModel>(this, bundle);
            SetContentView(Resource.Layout.PeriodDetailsLayout);
            Init();
        }

        protected override void OnResume()
        {
            base.OnResume();
            HookModel();
        }

        protected override void OnPause()
        {
            base.OnPause();
            UnhookModel();
        }

        private async void Init()
        {
            using (System.Threading.CancellationTokenSource cancellation = new System.Threading.CancellationTokenSource())
                await _model.LoadGoalsAsync(cancellation.Token);
        }

        private void HookModel()
        {
            if (_model == null)
                return;
            _model.CurrentGoalChanged += Model_CurrentGoalChanged;
            Button addGoalButton = FindViewById<Button>(Resource.Id.addGoalButton);
            EditText titleEditText = FindViewById<EditText>(Resource.Id.goalTitleEditText);
            addGoalButton.Click += (sender, e) => _model.AddNewGoal(titleEditText.Text);
            ListView goalsListView = FindViewById<ListView>(Resource.Id.goalsListView);
            goalsListView.Adapter = new GoalsAdapter(this, _model);
        }

        private void UnhookModel()
        {
            
        }

        private void Model_CurrentGoalChanged(object sender, EventArgs e)
        {
            UIHelper.GoActivity<GoalModel>(this, _model.CurrentGoal, typeof(GoalDetailsActivity));
        }
    }
}